package xyz.cerberu.cet.global.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

/**
 * @author β世界
 * @Name β世界
 * Created on 16:05
 * @Description 邮件发送服务
 */
@Component
public class EmailService {

    private final JavaMailSenderImpl mailSender;
    private final MailProperties mailProperties;
    private final static String SUBJECT = "CeT 注册验证码";

    @Autowired
    public EmailService(JavaMailSenderImpl mailSender, MailProperties mailProperties) {
        this.mailSender = mailSender;
        this.mailProperties = mailProperties;
    }

    /**
     * @author β世界 on 19:17 2020/7/1
     * 发送注册的验证码
     * @param code:验证码
     * @param to:接收的对象
     **/
    public void sendRegisterVerifyCode(String code,String to) throws javax.mail.MessagingException {
        String text =
                "<html>" +
                    "<body>" +
                        "<div style=\"font-size:20px;\">您的注册验证码是" +
                            "<span style=\"color:#0073FF;font-size:16px;margin: auto 10px auto 10px;\">"+code+"</span>" +
                            "注册码将在五分钟后过期,请尽快的填入并注册,感谢您的注册和使用</div>" +
                        "<span style=\"font-family: 'Nunito', Arial, Tahoma, Geneva, sans-serif; color: #aaaaaa; font-size: 16px; line-height: 32px;\">(如果您从未请求发送邮箱验证码，请忽略此邮件)</span>" +
                    "</body>" +
                "</html>";
        // 发送邮件
        sendMail(text,to);
    }

    private void sendMail(String text,String to) throws javax.mail.MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mailMessage = new MimeMessageHelper(mimeMessage);
        // 设置发件人
        mailMessage.setFrom(mailProperties.getUsername());
        // 设置发件人
        mailMessage.setTo(to);
        mailMessage.setSubject(SUBJECT);
        mailMessage.setText(text,true);
        // 发送邮件
        mailSender.send(mimeMessage);
    }

}
